import { ObjectUtil } from './ObjectUtil';
import { Overwrite } from '@/utils/types';

export const DateUtil = {
  equals: (a: Date, b: Date): boolean => a.getTime() === b.getTime(),

  format: (date: Date, format = 'yyyy-MM-dd HH:mm:ss'): string => {
    const o: { [key: string]: number } = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'H+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds(),
    };
    if (/(y+)/.test(format)) {
      format = format.replace(RegExp.$1, String(date.getFullYear()).substr(4 - RegExp.$1.length));
    }
    if (/(S+)/.test(format)) {
      format = format.replace(RegExp.$1, String('00' + date.getMilliseconds()).substr(-RegExp.$1.length));
    }
    for (const k in o) {
      if (new RegExp('(' + k + ')').test(format)) {
        format = format.replace(
          RegExp.$1,
          RegExp.$1.length === 1 ? String(o[k]) : ('00' + o[k]).substr(String(o[k]).length)
        );
      }
    }
    return format;
  },

  time: (date: string): Date => {
    const target = new Date(Date.parse(date));
    if (isNaN(target.getTime())) {
      throw new Error('无法将该字符串转化为时间');
    } else {
      return target;
    }
  },

  formatObject: <T, K extends keyof T>(o: T, keys: K[], format = 'yyyy-MM-dd HH:mm:ss'): Overwrite<T, K, string> => {
    /* eslint-disable-next-line */
    const clone = ObjectUtil.clone(o) as any;
    for (const key of keys) {
      const val = o[key];
      if (val instanceof Date) {
        clone[key] = DateUtil.format(val, format);
      }
    }
    return clone;
  },

  timeObject: <T, K extends keyof T>(o: T, keys: K[]): Overwrite<T, K, Date> => {
    /* eslint-disable-next-line */
    const clone = ObjectUtil.clone(o) as any;
    for (const key of keys) {
      const val = o[key];
      if (typeof val === 'string') {
        clone[key] = DateUtil.time(val);
      }
    }
    return clone;
  },
};
